package at.tugraz.akm.forume.extras;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public abstract class JSONUtils {

	/**
	 * 
	 * @param url
	 * @param key
	 * @return
	 */
	public static String getString(String url, String key) {
		JSONObject j = JSONUtils.getJSONObject(url);
		if (j != null) {
			try {
				return j.getString(key);
			} catch (JSONException e) {
				Log.e("Client.getString(" + url + ", " + key
						+ ") - JSONException", "" + e.getLocalizedMessage());
			}
		}
		return null;
	}

	/**
	 * Return a single boolean value. e.g: {"logged":"true"}
	 * 
	 * @param url
	 * @param key
	 * @return
	 */
	public static boolean getBoolean(String url, String key) {
		JSONObject j = JSONUtils.getJSONObject(url);
		if (j != null) {
			try {
				return j.getBoolean(key);
			} catch (JSONException e) {
				Log.e("Client.getBoolean(JSONObject j) - JSONException",
						"" + e.getLocalizedMessage());
			}
		}
		return false;
	}

	public static JSONObject getJSONObject(String url) {
		HttpResponse response;
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		try {
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			JSONObject j;

			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				return j;
			}
		} catch (ClientProtocolException e) {
			Log.e("Client.getJSONObject(" + url + ") - ClientProtocolException",
					"" + e.getLocalizedMessage());
		} catch (IOException e) {
			Log.e("Client.getJSONObject(" + url + ") - IOException",
					"" + e.getLocalizedMessage());
		} catch (IllegalStateException e) {
			Log.e("Client.getJSONObject(" + url + ") - IllegalStateException",
					"" + e.getLocalizedMessage());
		} catch (JSONException e) {
			Log.e("Client.getJSONObject(" + url + ") - JSONException",
					"" + e.getLocalizedMessage());
		} catch (Exception e) {
			Log.e("Client.getJSONObject(" + url + ") - Exception",
					"" + e.getLocalizedMessage());
		}
		return null;
	}

}
